if(dev) {
    console.info('加载', 'common.js');
}
(function ($) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };

    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
})(jQuery);


(function($)
{
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;

    $.extend({
        PIF_dateDiffFormat:
        {
            Info:{
                Name: "格式化时间差",
                Ver: "1.0.0.0",
                Corp: "fly_binbin",
                Author: "fly_binbin",
                Date: "2011-12-17",
                Email:"legend.binbin.fly@gmail.com",
                Copyright: "Copyright @ 2000-2010 fly_binbin Technology Software All Rights Reserved",
                License: "GPL"
            },

            getDateDiff: function (varparam,id) {
                var dateTimeStamp = varparam ? Date.parse(varparam.replace(/-/gi,"/")) : new Date().getTime();
                var date=new Date(dateTimeStamp);
                date.setHours(date.getHours()+8);//为了修正时区不一致问题
                var now = new Date().getTime();
                var diffValue = now - date.getTime();

                if(diffValue < 0){
                    //alert("结束日期不能小于开始日期！");
                }
                var monthC =diffValue/month;
                var weekC =diffValue/(7*day);
                var dayC =diffValue/day;
                var hourC =diffValue/hour;
                var minC =diffValue/minute;
                /*if(monthC >=1){
                    var fd=date.getFullYear(); //获取完整的年份(4位,1970-????)
                    var mon=date.getMonth()+1; //获取当前月份(0-11,0代表1月)
                    $("#"+id).html(mon+"/"+fd);
                    return;
                }
                else if(weekC>=1){
                    result= parseInt(weekC) + " weeks ago";
                }*/
                if(dayC>1){
                    var pyear =date.getFullYear();
                    var pmonth=date.getMonth()+1;
                    var pdate=date.getDate();
                    var phour=date.getHours();
                    var pmin=date.getMinutes();
                    var psecond=date.getSeconds();
                    if(String(pmonth).length==1){
                        pmonth="0"+String(pmonth);
                    }
                    if(String(pdate).length==1){
                        pdate="0"+String(pdate);
                    }
                    if(String(psecond).length==1){
                        psecond="0"+String(psecond);
                    }
                    $("#"+id).html(pyear+"/"+pmonth+"/"+pdate+" "+phour+":"+pmin+":"+psecond);
                    return;
                }
                else if(dayC==1){
                    result= "Yesterday";
                }
                else if(hourC>=1){
                    result=parseInt(hourC) +"h";
                }
                else if(minC>=1){
                    result=parseInt(minC) +"min";
                }else
                    result=" Just now";
                $("#"+id).html(result);
            },
            getDateAdd8Hour: function (varparam,id) {
                var dateTimeStamp = varparam ? Date.parse(varparam.replace(/-/gi,"/")) : new Date().getTime();
                var date=new Date(dateTimeStamp);
                date.setHours(date.getHours()+8);//为了修正时区不一致问题
                var pyear =date.getFullYear();
                var pmonth=date.getMonth()+1;
                var pdate=date.getDate();
                var phour=date.getHours();
                var pmin=date.getMinutes();
                var psecond=date.getSeconds();
                if(String(pdate).length==1){
                    pdate="0"+String(pdate);
                }
                if(String(psecond).length==1){
                    psecond="0"+String(psecond);
                }
                $("#"+id).html(pyear+"/"+pmonth+"/"+pdate+" "+phour+":"+pmin+":"+psecond);
            },
            getYearAndMonthAdd8Hour: function (varparam,id) {
                if(varparam==null||varparam==""||varparam==undefined){
                    $("#"+id).html("");
                    return;
                }
                var dateTimeStamp = varparam ? Date.parse(varparam.replace(/-/gi,"/")) : new Date().getTime();
                var date=new Date(dateTimeStamp);
                date.setHours(date.getHours()+8);//为了修正时区不一致问题
                var year =date.getFullYear();
                var month=date.getMonth()+1;
                if(String(month).length==1){
                    month="0"+String(month);
                }
                $("#"+id).html(year+"/"+month);
            },
            getYearAndMonthAndDateAdd8Hour: function (varparam,id) {
                var dateTimeStamp = varparam ? Date.parse(varparam.replace(/-/gi,"/")) : new Date().getTime();
                var date=new Date(dateTimeStamp);
                date.setHours(date.getHours()+8);//为了修正时区不一致问题
                var year =date.getFullYear();
                var month=date.getMonth()+1;
                var pdate=date.getDate();
                if(String(month).length==1){
                    month="0"+String(month);
                }
                if(String(pdate).length==1){
                    pdate="0"+String(pdate);
                }
                $("#"+id).html(year+"/"+month);
            }
        }
    });
})(jQuery);

function logout(){
    $.cookie("token","");
    window.location="login.html"
}
function addfavorite(paperid) {
    getData("POST", interfaces.favorite_add, false, '{"token":"' + $.cookie("token") + '","paperId":' + paperid + '}', "addfavorite","starnum"+paperid);
    countfavorite(paperid);
}
function countfavorite(paperid) {
    getReturnData(interfaces.favorite_count,true, '{"token":"' + $.cookie("token") + '","paperId":' + paperid + '}', 'starnum' + paperid, 'favoriteCount');
}
function countdownload(paperid) {
    getReturnData(interfaces.download_count,true, '{"token":"' + $.cookie("token") + '","paperId":' + paperid + '}', 'downloadnum' + paperid, 'downloadCount');
}
function adddownload(paperid,downloadurl) {
    if(dev){
        console.info(paperid);
        console.info(downloadurl);
    }
    if(downloadurl==null||downloadurl==undefined||downloadurl==""){
        //showDialog('Warn', "The PDF of the paper does not exist.");
        showUpload(paperid);//没有论文的时候弹出让他上传
    }else{
        window.open(downloadurl);
        getReturnData(interfaces.download_add, false,'{"token":"' + $.cookie("token") + '","paperId":' + paperid + '}', 'downloadnum2' + paperid, 'downloadCount');
        countdownload(paperid);
    }
}
function countcomment(paperid){
    getReturnData(interfaces.comment_count,true, '{"token":"' + $.cookie("token") + '","paperId":' + paperid + '}', 'commentnum' + paperid, 'commentCount');
}
function showcomment(paperid){
    if(paperid==null||paperid==undefined){
        showDialog('Warn', "Comments of the paper does not exist.");
        return;
    }else{
        window.location='comment.html?paperId='+paperid;
    }
}
function detail(paperid) {
    window.location = 'info.html?device=2&paperId=' + paperid;
}
function jumptodetail(urls){
    if(urls==null||urls==undefined){
        //alert("The source URL of the paper can not be found.");
        showDialog('Warn', "The source URL of the paper can not be found.");
    }else{
        if(dev){
            console.info(urls);
        }
        window.open(urls);
    }
}
function deleteComment(obj){
    var arr=$(obj).attr("data").split("-");
    var paperid=arr[0];
    var commentid=arr[1];
    getDataThenRefresh(interfaces.comment_del, '{"token":"' + $.cookie("token") + '","commentId":' + commentid + '}', "delcomment",paperid);
}

function deleteNews(obj){
    var newsid=$(obj).attr("data");
    getDataThenRefresh(interfaces.comment_del, '{"token":"' + $.cookie("token") + '","commentId":' + newsid + '}', "delnews");
}

function showUpload(paperid){
    var d = dialog({
        title: "Upload",
        content: '',
        width:320,
        height:120,
        okValue: 'OK'
    });
    d.content($('#fine-uploader-validation')[0]);
    $("#upload_paperid").val(paperid);
    d.show();
}
function upload2Server() {
    $(".uploadButton").val("Select");
    var paperid=$("#upload_paperid").val();
    // 上传方法
    $.upload({
        // 上传地址
        url: interfaces.uploadfile,
        // 文件域名字
        fileName: 'file',
        // 其他表单数据
        params: {token: $.cookie("token"),paperId:paperid},
        // 上传完成后, 返回json, text
        dataType: 'json',
        // 上传之前回调,return true表示可继续上传
        onSend:function(){
            return true;
        },
        onSubmit: function() {
            var filepath=$("input[name='file']").val();
            var extStart=filepath.lastIndexOf(".");
            var ext=filepath.substring(extStart+1,filepath.length).toUpperCase();
            if(ext!=="PDF"||ext==null||ext==""||ext==undefined){
                showDialog("Warn","Only PDF!!");
                return false;
            }
            var file = $("input[name='file']").get(0).files[0];
            if (file) {
                var fileSize = 0;
                if (file.size > 1024 * 1024)
                    fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                else
                    fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
                if(dev){
                    console.log(file.name, fileSize, file.type);
                }
                $("#filepath").val(filepath);
                if(file.size>1024 * 1024*10){
                    showDialog("Warn","Must less than 10M!!");
                    return false;
                }
            }
            $(".uploadButton").css("background-color","darkgrey");
            $(".uploadButton").attr("disabled",true);
            $(".uploadButton").val("Uploading...");
            return true;
        },
        // 上传之后回调
        onComplate: function(data) {
            if(dev){
                console.info(data);
            }
            $(".uploadButton").css("background-color","#4AFF00");
            $(".uploadButton").removeAttr("disabled");
            $(".uploadButton").val("Select");
            $("#filepath").val("");
            if(data.status==200){
                var downloadurl=data.result.downloadUrl;
                var indx=downloadurl.indexOf('/',8);
                window.open(downloadurl.substr(indx));
                clearAllDialog();
                showDialog("Success","Upload Success");
            }else{
                showDialog("Warn",data.errors);
            }

            /*window.setTimeout(function(){
                window.location.href=window.location.href;
            },30000);*/
        }
    });
}
function clearAllDialog(){
    var list = dialog.list;
    for (var i in list) {
        list[i].close();
    }
}

function authorsPapers(author){
    window.location='/authorpapers.html?author='+author;
}
// 一些内部辅助函数
function getReturnData(url,async, _data, jfavid, wname,removeclass,addclass) {
    $.ajax({
        type: 'POST',
        url: url,
        data: _data,
        async: async,
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        beforeSend: function () {
            //document.getElementById('light').style.display='block';
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if(dev) {
                console.info(XMLHttpRequest.status);
                console.info(XMLHttpRequest.readyState);
                console.info(textStatus);
            }
            showDialog('Warn', "network error!");
        },
        success: function (data) {
            var num=data.result[wname];
            $("#" + jfavid).text(num);
            if(jfavid.indexOf('starnum')>-1){
                var isCollect=data.result.isCollect;
                if(isCollect){//收藏
                    $("#" + jfavid).removeClass('starnum').addClass('starnumed');
                }else{
                    $("#" + jfavid).removeClass('starnumed').addClass('starnum');
                }
            }
            if(jfavid.indexOf('downloadnum')>-1){
                var isDownload=data.result.isDownload;
                if(isDownload){
                    $("#" + jfavid).removeClass('downloadnum').addClass('downloadnumed');
                }else{
                    $("#" + jfavid).removeClass('downloadnumed').addClass('downloadnum');
                }
            }
        }
    });
}
function getData(typed, url, async, data, callbacktype) {
    $.ajax({
        type: 'POST',
        url: url,
        async: async,
        data: data,
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        beforeSend: function () {
            //document.getElementById('light').style.display='block';
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if(dev) {
                console.info(XMLHttpRequest.status);
                console.info(XMLHttpRequest.readyState);
                console.info(textStatus);
            }
            showDialog('Warn', "network error!");
        },
        success: function (data) {
            callback(callbacktype, data);
        }
    })
}
function getDataThenRefresh( url, data, callbacktype ,refreshid) {
    $.ajax({
        type: 'POST',
        url: url,
        async: true,
        data: data,
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        beforeSend: function () {
            //document.getElementById('light').style.display='block';
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if(dev) {
                console.info(XMLHttpRequest.status);
                console.info(XMLHttpRequest.readyState);
                console.info(textStatus);
            }
            showDialog('Warn', "network error!");
        },
        success: function (data) {
            callbackrefresh(callbacktype, data,refreshid);
        }
    })
}
function callbackrefresh(type,data,refreshid){
    if(type=="addcomment"){
        window.location='comment.html?paperId='+refreshid;
    }
    if(type=="delcomment"){
        if(data.status==200){
            if(dev){
                console.info(data.result);
            }
            window.location="comment.html?paperId="+refreshid;
        }else{
            showDialog('Warn', data.errors);
        }
    }
    if(type=="delnews"){
        if(data.status==200){
            if(dev){
                console.info(data.result);
            }
            window.location="news.html";
        }else{
            showDialog('Warn', data.errors);
        }
    }
}
function callback(type, data) {
    if (type == "login") {
        if(dev) {
            console.info(data);
        }
        if (data.status == 200) {
            if(dev) {
                console.info("登陆成功");
            }
            $.cookie('token', data.result.token);
            window.location = "recommend.html";
        } else {
            showDialog('Warn', data.errors);
            return;
        }
    }
    if (type == "register") {
        if (data.status == 200) {
            $('.signup').hide();
            if(dev) {
                console.info("注册成功");
            }
            showDialog('Success', 'SignUp Success!');
            $("#username").val($("#email").val());
        } else {
            showDialog('Warn', data.errors);
            return;
        }
    }
    if (type == "userinfo") {
        if(dev) {
            console.info("获取用户基本信息", data);
        }
        if (data.status == 200) {
            var username = data.result.username;
            $(".username").html(username);
        } else {
            window.location = "login.html"
        }
    }
    if (type == "addfavorite") {
        if(data.status==200&&data.result.id<0){
            showDialog('Success', 'Cancel Favorites Success!');
            //$("#"+callbackid).removeClass('starnumed').addClass('starnum');
        }else{
            showDialog('Success', 'Favorites Success!');
            //$("#"+callbackid).removeClass('starnum').addClass('starnumed');
        }

    }
    if(type=="addnews"){
        window.location='news.html'
    }
    if(type=="settings"){
        if(data.status==200){
            var username=data.result.username;
            var firstName=data.result.firstName;
            var middleName=data.result.middleName;
            var lastName=data.result.lastName;
            var email=data.result.email;
            //var gender=data.result.gender;
            var location=data.result.position;
            //var phone=data.result.phone;
            var website=data.result.homepage;
            var interests=data.result.interests;
            var organ=data.result.department;
            var institution=data.result.institution;
            var department=data.result.department;
            //$('#name').val(username);
            $('#firstName').val(firstName);
            $('#middleName').val(middleName);
            $('#lastName').val(lastName);
            $('#email').val(email);
            //$('#gender').val(gender);
            $('#location').val(location);
            //$('#phone').val(phone);
            $('#website').val(website);
            $('#organ').val(organ);
            $('#interests').val(interests);

            $('#institu').val(institution);
            $('#department').val(department);

            $('#interests').tagEditor({
                initialTags: interests,
                delimiter: ',',
                placeholder: 'If inputting multi-interest, use ‘Enter’ key please.',
                onChange: function(field, editor, tags) { $('#interests').text((tags.length ? tags.join(',') : '')); }

            }).attr('readonly', true);
        }
    }
    if(type=="settings2"){
        if(data.status==200){
            showDialog('Success', 'Save Setting Success!');
        }else{
            showDialog('Error', 'Save Setting Error!');
        }
    }
    if(type=="download_hot"){
        if(data.status==200&&data.result.hotPapers!=null){
            if(dev) {
                console.info(data.result);
            }
            var li="";
            $.each(data.result.hotPapers,function(i){
                if(dev) {
                    console.info(i + ":", this.paper.title);
                }
                li+='<li>'+
                '<span class="index">'+(i+1)+'.</span>'+
                    '<span class="content"><a href="javascript:void(0);" onclick="detail('+this.paper.id+');">'+this.paper.title+'</a></span>'+
                '</li>';
            });
            $("#downhot").empty();
            $("#downhot").append(li);
        }
    }
    if(type=="favorite_hot"){
        if(data.status==200){
            if(dev) {
                console.info(data.result);
            }
            var li="";
            $.each(data.result.hotPapers,function(i){
                if(dev) {
                    console.info(i + ":", this.paper.title);
                }
                li+='<li>'+
                    '<span class="index">'+(i+1)+'.</span>'+
                    '<span class="content"><a href="javascript:void(0);" onclick="detail('+this.paper.id+');">'+this.paper.title+'</a></span>'+
                    '</li>';
            });
            $("#favoritehot").empty();
            $("#favoritehot").append(li);
        }
    }
    if(type=="account_favorite_count"){
        if(data.status==200){
            if(dev) {
                console.info(data.result);
            }
            $("#account_favorite_count").html(data.result.favoriteCount);
        }
    }
    if(type=="account_download_count"){
        if(data.status==200){
            if(dev) {
                console.info(data.result);
            }
            $("#account_download_count").html(data.result.downloadCount);
        }
    }
    if(type=="account_comment_count"){
        if(data.status==200){
            if(dev) {
                console.info(data.result);
            }
            $("#account_comment_count").html(data.result.commentCount);
        }
    }
    if(type=="account_comment_unread_count"){
        if(data.status==200){
            if(dev) {
                console.info(data.result);
            }
            var commentCount=data.result.commentCount;
            if(commentCount==0){
                $("#account_comment_unread_count").hide();
            }else{
                $("#account_comment_unread_count").show();
                $("#account_comment_unread_count").html(data.result.commentCount);
            }

        }
    }

    if(type=="setpassword"){
        if(data.status==200){
            if(dev){
                console.info(data.result);
            }
            showDialog('Success', 'Set Password Success!');
        }
    }
    if(type=="findpassword"){
        if(data.status==200){
            if(dev){
                console.info(data.result);
            }
            showDialog('Success', 'Send Email Success!');
        }
    }
}
function showDialog(title, content) {
    clearAllDialog();
    var d = dialog({
        title: title,
        content: '',
        //width:320,
        //height:120,
        okValue: 'OK',
        time:2
    });
    d.content("<div class='content_center'>"+content+"</div>");
    d.show();
}

$(window).resize(function() {
    try{
        var search_y = $('.search').position().left;
        $(".autocompleter").css("marginLeft",search_y);
    }catch (e){

    }

});